package com.hzw.controller;

import com.hzw.bean.ApiResult;
import com.hzw.service.PhotoUploadService;
import com.hzw.utils.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.hzw.api.Api.CLIENT_ERROR;
import static com.hzw.api.Api.SERVER_ERROR;

/**
 * Created by Administrator on 2019/3/7.
 */
@Controller
@RequestMapping(value = "/photo",method = RequestMethod.POST)
public class PhotoUploadController{
    @Resource
    private PhotoUploadService photoUploadService;

    @RequestMapping(value = "/upload")
    @ResponseBody
    public ApiResult photoUpload(@RequestParam(value = "myFile")MultipartFile multipartFile,
                                                                            HttpServletRequest request){

        ApiResult result = new ApiResult();
        List<String> photoSrc = null;

        String userName = request.getParameter("userName");     //获取用户名用于后面创建文件夹名字

        if(ObjectUtils.isNullOrEmpty(multipartFile)){
            result.error(CLIENT_ERROR,"图片不能为空");
            return result;
        }else if(ObjectUtils.isNullOrEmpty(userName)){
            result.error(CLIENT_ERROR,"用户名不能为空");
            return result;
        }else{
            try {
                photoSrc = photoUploadService.photoUpload(multipartFile,userName);
                result.setData(photoSrc);
            } catch (Exception e) {
                result.error(SERVER_ERROR, e.getMessage());
                return result;
            }
        }
        return result;
    }
}
